<?php
// 应用公共文件
use app\common\model\Manage;
use app\common\model\User;

/**
 * 功能描述: 格式化API数据
 * @author 救火队队长
 */
function show($status,$msg = "",$datas = [],$httpStatus = 200){

    $result = [
        'code' => $status,
        'msg'    => $msg,
        'data'  => $datas
    ];

    return json($result,$httpStatus);
}


/***
 * 令牌校检
 * @author 救火队队长
 * @return array
 */
function validateShopToken()
{
    $_token = input('__token__/s', '');

    if (!$_token || $_token != session('__token__')) {

        if (request()->isAjax()) {
            $return = [
                'data'   => '',
                'msg'    => '已超时或重复提交，请重试或刷新页面',
                'status' => false,
                'token'  => ''
                //'token'  => request()->buildToken('__token__', 'sha1')
            ];

            header('Content-type:text/json');
            echo json_encode($return);
            exit;
        } else {
            die("CSRF is die");
        }
    }

}

/**
 * 生成令牌
 * @author 救火队队长
 */
function shopToken()
{
    $data = request()->buildToken('__token__', 'sha1');
    return '<input type="hidden" name="__token__" value="' . $data . '" class="token">';
}


/**
 * 返回当前的毫秒时间戳
 * @author 救火队队长
 * @return string
 */
function msectime()
{
    list($tmp1, $tmp2) = explode(' ', microtime());
    return sprintf('%.0f', (floatval($tmp1) + floatval($tmp2)) * 1000);
}

/**
 * 获取最近天数的日期和数据
 * @author 救火队队长
 * @param $day
 * @param $data
 * @return array
 */
function get_lately_days($day, $data)
{
    $day  = $day - 1;
    $days = [];
    $d    = [];
    for ($i = $day; $i >= 0; $i--) {
        $d[] = date('d', strtotime('-' . $i . ' day')) . '日';
        $days[date('Y-m-d', strtotime('-' . $i . ' day'))] = 0;
    }
    foreach ($data as $v) {
        $days[$v['day']] = $v['nums'];
    }
    $new = [];
    foreach ($days as $v) {
        $new[] = $v;
    }
    return ['day' => $d, 'data' => $new];
}


/**
 * 获取客户端IP地址
 * @author 救火队队长
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function get_client_ip($type = 0, $adv = false)
{
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL) return $ip[$type];
    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) unset($arr[$pos]);
            $ip = trim($arr[0]);
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}


/**
 * 判断前端浏览器类型
 * @author 救火队队长
 * @return bool|string
 */
function get_client_broswer()
{
    $ua = $_SERVER['HTTP_USER_AGENT'];

    //微信内置浏览器
    if (stripos($ua, 'MicroMessenger')) {
        //preg_match('/MicroMessenger\/([\d\.]+)/i', $ua, $match);
        return "weixin";
    }
    //支付宝内置浏览器
    if (stripos($ua, 'AlipayClient')) {
        //preg_match('/AlipayClient\/([\d\.]+)/i', $ua, $match);
        return "alipay";
    }
    return false;
}


/**
 * 数组倒排序，取新的键
 * @author 救火队队长
 * @param array $array
 * @return array
 */
function _krsort($array = [])
{
    krsort($array);
    if (is_array($array)) {
        $i          = 0;
        $temp_array = [];
        foreach ($array as $val) {
            $temp_array[$i] = $val;
            $i++;
        }
        return $temp_array;
    } else {
        return $array;
    }
}

/**
 * 返回错误码
 * @author 救火队队长
 * @param $code
 * @param bool $mini
 * @return array|mixed
 */
function error_code($code, $mini = false)
{
    $result = [
        'status' => 10000,
        'msg'    => config('error.10000'),
        'datas'   => [],
    ];

    if (config('?error.' . $code)) {
        $result['status'] = $code;
        $result['msg']  = config('error.' . $code);
    }

    if ($mini) {
        return $result['msg'];
    } else {
        return $result;
    }

}

/**
 * 生成编号
 * @author 救火队队长
 * @param $type
 * @return string
 */
function get_sn($type)
{
    switch ($type) {
        case 1:         //订单编号
            $str = $type . substr(msectime() . rand(0, 9), 1);
            break;
        case 2:         //支付单编号
            $str = $type . substr(msectime() . rand(0, 9), 1);
            break;
        case 3:         //商品编号
            $str = 'G' . substr(msectime() . rand(0, 5), 1);
            break;
        case 4:         //货品编号
            $str = 'P' . substr(msectime() . rand(0, 5), 1);
            break;
        case 5:         //售后单编号
            $str = $type . substr(msectime() . rand(0, 9), 1);
            break;
        case 6:         //退款单编号
            $str = $type . substr(msectime() . rand(0, 9), 1);
            break;
        case 7:         //退货单编号
            $str = $type . substr(msectime() . rand(0, 9), 1);
            break;
        case 8:         //发货单编号
            $str = $type . substr(msectime() . rand(0, 9), 1);
            break;
        case 9:         //提货单号
            //$str = 'T'.$type.substr(msectime().rand(0,5), 1);
            $chars    = ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '2', '3', '4', '5', '6', '7', '8', '9'];
            $charsLen = count($chars) - 1;
            shuffle($chars);
            $str = '';
            for ($i = 0; $i < 6; $i++) {
                $str .= $chars[mt_rand(0, $charsLen)];
            }
            break;
        default:
            $str = substr(msectime() . rand(0, 9), 1);
    }
    return $str;
}

/***
 * 获取年月日目录
 * @author 救火队队长
 */
function get_date_dir()
{
    $dir = '/' . date('Y') . '/' . date('m') . '/' . date('d');
    return $dir;
}

/**
 * 时间格式化
 * @author 救火队队长
 * @param int $time
 * @return false|string
 */
function getTime($time = 0)
{
    return date('Y-m-d H:i:s', $time);
}

/**
 * 返回用户信息
 * @author 救火队队长
 * @param $user_id
 * @param string $field
 * @return string
 */
function get_user_info($user_id, $field = 'mobile')
{
    if (!$user_id) {
        return "";
    }
    $user = app\common\model\User::get($user_id);
    if ($user) {
        if ($field == 'nickname') {
            $nickname = $user['nickname'];
            if ($nickname == '') {
                $nickname = format_mobile($user['mobile']);
            }
            return $nickname;
        } else {
            return $user->$field;
        }
    } else {
        return "";
    }
}

/**
 * 返回用户信息
 * @author 救火队队长
 * @param $mobile
 * @return bool|mixed
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function get_user_id($mobile)
{
    $userModel = new app\common\model\User();
    $user      = $userModel->where(array('mobile' => $mobile))->find();
    if ($user) {
        return $user->id;
    } else {
        return false;
    }
}


/**
 * 返回管理员信息
 * @author 救火队队长
 * @param $manage_id
 * @param string $field
 * @return string
 */
function get_manage_info($manage_id, $field = 'username')
{
    $user = app\common\model\Manage::find($manage_id);
    if ($user) {
        if ($field == 'nickname') {
            $nickname = $user['nickname'];
            if ($nickname == '') {
                $nickname = format_mobile($user['mobile']);
            }
            return $nickname;
        } else {
            return $user->$field;
        }
    } else {
        return "";
    }
}

/***
 * 判断是否json
 * @author 救火队队长
 * @param $str
 * @return bool
 */
function isjson($str)
{
    return is_null(json_decode($str)) ? false : true;
}

/**
 * 格式化数据化手机号码
 * @author 救火队队长
 * @param $mobile
 * @return string
 */
function format_mobile($mobile)
{
    return substr($mobile, 0, 5) . "****" . substr($mobile, 9, 2);
}


/**
 * 判断是否手机号
 * @author 救火队队长
 * @param $mobile
 * @return bool
 */
function isMobile($mobile = '')
{
    if (preg_match("/^1[3456789]{1}\d{9}$/", $mobile)) {
        return true;
    } else {
        return false;
    }
}


/**
 * 秒转换为天，小时，分钟
 * @author 救火队队长
 * @param int $second
 * @return string
 */
function secondConversion($second = 0)
{
    $newtime = '';
    $d       = floor($second / (3600 * 24));
    $h       = floor(($second % (3600 * 24)) / 3600);
    $m       = floor((($second % (3600 * 24)) % 3600) / 60);
    if ($d > '0') {
        if ($h == '0' && $m == '0') {
            $newtime = $d . '天';
        } else {
            $newtime = $d . '天' . $h . '小时' . $m . '分';
        }
    } else {
        if ($h != '0') {
            if ($m == '0') {
                $newtime = $h . '小时';
            } else {
                $newtime = $h . '小时' . $m . '分';
            }
        } else {
            $newtime = $m . '分';
        }
    }
    return $newtime;
}


/**
 * 返回图片地址
 * @author 救火队队长
 */
function _sImage($image_id = '', $type = 's')
{
    if (!$image_id) {
        $image_id = getSetting('shop_default_image');//系统默认图片
        if (!$image_id) {
            return config('shop.default_image');//默认图片
        }
    }

    if (stripos($image_id, 'http') !== false || stripos($image_id, 'https') !== false) {
        return $image_id;
    }

    $image_obj = new \app\common\model\Images();
    $image     = $image_obj->where([
        'id' => $image_id
    ])->field('url')->cache(true)->find();
    if ($image) {
        if (stripos($image['url'], 'http') !== false || stripos($image['url'], 'https') !== false) {
            return str_replace("\\", "/", $image['url']);
        } else {
            return request()->domain() . str_replace("\\", "/", $image['url']);
        }
    } else {
        return config('shop.default_image');//默认图片
    }
}


/**
 * 相对地址转换为绝对地址
 * @author 救火队队长
 * @param string $url
 * @return string
 */
function getRealUrl($url = '')
{
    if (stripos($url, 'http') !== false || stripos($url, 'https') !== false) {
        return $url;
    } else {
        $storage_params = getSetting('image_storage_params');
        if (isset($storage_params['domain']) && $storage_params['domain']) {
            return $storage_params['domain'] . $url;
        }
        if (config('shop.image_storage.domain')) {
            return config('shop.image_storage.domain') . $url;
        }
        return request()->domain() . $url;
    }
}

/**
 * 获取hash值
 * @author 救火队队长
 * @return string
 */
function get_hash()
{
    $chars   = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()+-';
    $random  = $chars[mt_rand(0, 73)] . $chars[mt_rand(0, 73)] . $chars[mt_rand(0, 73)] . $chars[mt_rand(0, 73)] . $chars[mt_rand(0, 73)];
    $content = uniqid() . $random;
    return sha1($content);
}


/**
 * 获取系统设置
 * @author 救火队队长
 * @param string $key
 * @return mixed|string
 */
function getSetting($key = '')
{
    $systemSettingModel = new \app\common\model\Setting();
    return $systemSettingModel->getValues($key);
}


/**
 * 获取多个系统设置
 * @author 救火队队长
 * @param string $key //多个英文逗号分隔
 * @return array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function getMultipleSetting($key = '')
{
    $systemSettingModel = new \app\common\model\Setting();
    return $systemSettingModel->getMultipleValue($key);
}

//---------------------------------------------------20210406--hz_add---------------------------------------------------
/**
 * CURL请求(返回code)
 * @param string $url 请求url地址
 * @param string $method 请求方法 get post
 * @param null $postfields  post数据数组
 * @param array $headers 请求header信息
 * @param bool $debug 调试开启 默认false
 * @param int $timeout 请求方法 get post
 * @return array
 */

function http_request($url, $method = "GET", $postfields = null, $headers = array(), $debug = false , $timeout = 10)
{
    $method = strtoupper($method);
    $ci = curl_init();
    /* Curl settings */
    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
    //目标服务器响应时间
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $timeout); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
    //本地服务器执行时间
    curl_setopt($ci, CURLOPT_TIMEOUT, $timeout); /* 设置cURL允许执行的最长秒数 */
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
    switch ($method) {
        case "POST":
            curl_setopt($ci, CURLOPT_POST, true);
            if (!empty($postfields)) {
                $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
            }
            break;
        case "PUT":
            curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method);
            curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
            break;
        default:
            curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
            break;
    }
    $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;

    curl_setopt($ci, CURLOPT_URL, $url);
    if ($ssl) {
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
    }
    //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
    curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ci, CURLINFO_HEADER_OUT, true);
    /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
    $response = curl_exec($ci);
    $requestinfo = curl_getinfo($ci);
    $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
    //$debug = true;
    if ($debug) {
        echo "=====post data======" . PHP_EOL;
        var_dump($postfields);
        echo "=====info=====" . PHP_EOL;
        print_r($requestinfo);
        echo "=====response=====" . PHP_EOL;
        print_r($response);
        echo "=====code=====" . PHP_EOL;
        print_r($http_code);
    }
    curl_close($ci);
    return [
        'code'          => $http_code,
        'response'      => $response
    ];
}

/**
 * 生成不重复的随机数字
 * @param int $start 需要生成的数字开始范围
 * @param int $end 结束范围
 * @param int $length 需要生成的随机数个数
 * @return number 生成的随机数
 */
function getRandNumber($start=0,$end=9,$length=10){
//初始化变量为0
    $connt = 0;
//建一个新数组
    $temp = array();
    while($connt < $length){
//在一定范围内随机生成一个数放入数组中
        $temp[] = mt_rand($start, $end);
//$data = array_unique($temp);
//去除数组中的重复值用了“翻翻法”，就是用array_flip()把数组的key和value交换两次。这种做法比用 array_unique() 快得多。
        $data = array_flip(array_flip($temp));
//将数组的数量存入变量count中
        $connt = count($data);
    }
//为数组赋予新的键名
    shuffle($data);
//数组转字符串
    $str=implode(",", $data);
//替换掉逗号
    $number=str_replace(',', '', $str);
    return $number;
}

/**
 * 解密字符串
 * @param string $data 字符串
 * @return false|string
 */
function decryptOpenssl($data){
    $method = 'DES-ECB';//加密方法
    $passwd = 'cpuPayMent20210302888';//加密密钥
    return openssl_decrypt($data, $method, $passwd);
}

/**
 * 加密字符串
 * @param string $data 字符串
 * @return string
 */
function encryptOpenssl($data){
    $method = 'DES-ECB';//加密方法
    $passwd = 'cpuPayMent20210302888';//加密密钥
    return openssl_encrypt($data, $method, $passwd);
}

function setToken($phone){
    $str = md5(uniqid(md5(microtime(true)),true));
    $token = sha1($str.$phone);
    return $token;
}

function ip(){
    $ip='UnKnow IP';
    if(!empty($_SERVER['HTTP_CLIENT_IP'])){
        return is_ip($_SERVER['HTTP_CLIENT_IP'])?$_SERVER['HTTP_CLIENT_IP']:$ip;
    }elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
        return is_ip($_SERVER['HTTP_X_FORWARDED_FOR'])?$_SERVER['HTTP_X_FORWARDED_FOR']:$ip;
    }else{
        return is_ip($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:$ip;
    }
}
function is_ip($str){
    $ip=explode('.',$str);
    for($i=0;$i<count($ip);$i++){
        if($ip[$i]>255){
            return false;
        }
    }
    return preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/',$str);
}

function getBetterParam($type)
{
    $array = [];
    switch ($type){
        case 'status':
            $array = ['AL','AK','AZ','AR','CO','CA','CT','DE','DC','FL','GA','HI','ID','IL','IN','IA',
                'KS','KY','LA','ME','MA','MD','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH',
                'OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY'];
            break;
        case 'incorporation_type':
            $array = ['LLC','CORPORATION','SOLE_PROPRIETORSHIP','PARTNERSHIP','COOPERATIVE','OTHER'];
            break;
        case 'about_us_question':
            $array = ['Ad(Google,etc.)','Blog Article','Email Newsletter','From a Friend','Online search(Google,Bing,etc.)',
                'Print Publication', 'Regular mail','Social Media','Tradeshow/Event','Small Business Expo'];
            break;
        case 'company_size':
            $array = ['1','2-5','6-10','11-20','21-50','50+'];
            break;
        case 'industry_subcategory':
            $array = ['Membership services','Services not elsewhere classified'];
            break;
        case 'industry':
            $array = ['Food retail and service','Manufacturing','Business to business','Services-other','Entertainment and media','Home and garden',
                'Baby','Travel','Clothing,accessories,and shoes','Health and personal care','Beauty and fragrances',
                'Computers, accessories, and services', 'Retail','Toys and hobbies','Pets and animals','Education',
                'Arts,crafts,and collectibles','Financial services and products', 'Government','Vehicle sales','Nonprofit',
                'Vehicle service and accessories','Electronics and telecom','Books and magazines',
                'Religion and spirituality (for profit)','Sports and outdoors','Gifts and flowers'];
            break;
        case 'business_structure':
            $array = ['Sole proprietorship','Partnership','Limited Liability Company','S Corporation','C Corporation','Nonprofit'];
            break;

    }
    return $array;
}

function getUtcTime($type=true)
{
    //这里cofig-app.php 设置默认时区为北京时间UTC+8，但是以消费时间为准 UTC-5 ，也就是要减13小时
    $str = strtotime(date('Y-m-d H:i:s')) - 13*60*60;
    if($type){
        return $str;
    }else{
        return date('Y-m-d H:i:s',$str);
    }
}

function getUtcYmdTime()
{
    return date('Y-m-d' , getUtcTime());
}

function getUtcMoneyTime($exchange_time='')
{
    switch ($exchange_time) {
        case 2 : // 上个月
            // 上个月的起始时间:
            $begin_time = strtotime('-1 month');
            $end_time = strtotime(-date('d').'day');
            break;
        case 3 : // 上上个月
            $begin_time =  mktime(0, 0 , 0,date("m")-2,1,date("Y"));
            $end_time =  mktime(23,59,59,date("m")-1 ,0,date("Y"));
            break;
        default:
            // 本月起始时间:
            $begin_time = mktime ( 0, 0, 0, date ( "m" ), 1, date ( "Y" )  );
            $end_time = mktime ( 23, 59, 59, date ( "m" ), date ( "t" ), date ( "Y" ) );
            break;
    }
    return [
        'start_time' => $begin_time - 13*60*60,
        'end_time'   => $end_time   - 13*60*60
    ];
}



function getSprintf($param)
{
    return sprintf("%.2f", $param);
}

/**
 * 验证参数
 * @param $param
 * @param $type
 * @return bool
 */
function check_param($param,$type)
{
    if(empty($param) || empty($type))return false;
    $pattern = "";
    switch ($type){
        case 'email':   //验证邮箱
            $pattern = "/([a-z0-9]*[-_.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?/i";
            break;
        case 'nickname': //验证昵称
            $pattern = "/^[a-zA-Z ]*$/";
            break;
        case 'zInt':
            $pattern = "/^[1-9]\d*$/";
            break;
        case 'zfInt':
            $pattern = "/^-?[1-9]\d*$/";
            break;
        case 'phone':
            $pattern = "/^\d{3}-\d{3}-\d{4}$/";
            break;
        case 'date':
            $pattern = "/^\d{4}-\d{2}-\d{2}$/";
            break;
        case 'card_name':
            $pattern = "/^[a-zA-Z][a-zA-Z ]{4,14}$/";
            break;
        case 'password':
            $pattern = "/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{12,32}$/";
            break;
        case 'zs_two':
            //非零开头的最多带两位小数的数字：
            $pattern = "/^([1-9][0-9]*)+(\.[0-9]{1,2})?$/";
            break;
        case 'user_card':
            $pattern = "/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/";
            break;
        case 'en':
            $pattern = "/^[a-zA-Z]+$/";
            break;
        case 'zn':
            $pattern = "/[\x{4e00}-\x{9fa5}]/u";
            break;
    }
    return (bool)preg_match($pattern , $param);
}

/**
 * 生成随机6位数字
 * @return string
 */
function nonceStr() {
    static $seed = array(0,1,2,3,4,5,6,7,8,9);
    $str = '';
    for($i=0;$i<6;$i++) {
        $rand = rand(0,count($seed)-1);
        $temp = $seed[$rand]; $str .= $temp;
        unset($seed[$rand]);
        $seed = array_values($seed);
    }
    return $str;
}

function getCardToken()
{
    //demo : 35bf65e3-608f-4ccd-a91e-12e3ff077374
    // 8-4-4-4-12    36位
    $card_token = randomkeys(8);
    $card_token .= '-' . randomkeys(4);
    $card_token .= '-' . randomkeys(4);
    $card_token .= '-' . randomkeys(4);
    $card_token .= '-' . randomkeys(12);
    return $card_token;
}

function randomkeys($length) {
    $returnStr='';
    $pattern = '1234567890abcdefghijklmnopqrstuvwxyz';
    for($i = 0; $i < $length; $i ++) {
        $returnStr .= $pattern {mt_rand ( 0, 31 )}; //生成php随机数
    }
    return $returnStr;
}

function randomSecretkeys($length) {
    $returnStr='';
    $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    for($i = 0; $i < $length; $i ++) {
        $returnStr .= $pattern {mt_rand ( 0, 60 )}; //生成php随机数
    }
    return $returnStr;
}

function random_first_name()
{
    $list = array("James","Joe","John","Juan","Robert","Jack","Albert","David","Terry",
        "Charles","Gerald","Joseph","Samuel","Willie","Ralph","Paul","Mark",
        "Donald",'Roy','George','Bruce','Steven','Edward','Adam','Brian','Harry','Ronald',
        'Fred','Wayne','Kevin','Billy','Jason','Steve','Louis','Gary','Jeremy','Aaron','Jose','Randy',
        'Larry','Howard','Eugene','Frank','Carlos','Scott','Eric','Bobby','Victor','Martin',
        'Ernest','Joshua','Todd','Jerry','Jesse','Craig','Walter','Alan','Shawn','Peter',
        'Harold','Sean','Philip','Henr','Chris','Carl','Johnny','Arthur','Earl','Ryan','Jimmy','Roger');
    $frist_num = mt_rand(0,70);
    return $list[$frist_num];
}
function random_last_name()
{
    $list = array('Smith','Bailey','Jones','Parker','Taylor','Miller','Davis','Brown','Murphy',
        'Davies','Price','Evans','Bell','Wilson','Baker','Thomas','Kelly','Simpson','Lewis','Walker',
        'Collins','Bennett', 'Wood','Cox','White','Fox','Watson','Gray','Jackson','Rose','Wright',
        'Chapman','Green','Hunt', 'Harris','Cooper','Shaw','King','Reynolds','Lee','Lloyd','Martin','Ellis',
        'Clarke','James','Morgan', 'Hughes','Khan','Edwards','Graham','Hill', 'Moore','Reid','Clark',
        'Murray','Powell','Scott', 'Palmer','Young','Holmes','Morris','Rogers', 'Hall','Ward','Walsh',
        'Turner','Hunter','Carter', 'Ross','Adams','Mason','Knight','Allen','Butler','Cook');
    $last_num = mt_rand(0,70);
    return $list[$last_num];
}

function random_user()
{
    $male_names = array("James","Joe","John","Juan","Robert","Jack","Albert","David","Terry",
        "Charles","Gerald","Joseph","Samuel","Willie","Ralph","Paul","Mark",
        "Donald",'Roy','George','Bruce','Steven','Edward','Adam','Brian','Harry','Ronald',
        'Fred','Wayne','Kevin','Billy','Jason','Steve','Louis','Gary','Jeremy','Aaron','Jose','Randy',
        'Larry','Howard','Eugene','Frank','Carlos','Scott','Eric','Bobby','Victor','Martin',
        'Ernest','Joshua','Todd','Jerry','Jesse','Craig','Walter','Alan','Shawn','Peter',
        'Harold','Sean','Philip','Henr','Chris','Carl','Johnny','Arthur','Earl','Ryan','Jimmy','Roger');
    $famale_names = array('Mary','Alice','Julie','Linda','Teresa','Doris','Gloria','Maria','Evelyn',
        'Susan','Jean','Cheryl','Lisa','Nancy','Joan','Karen','Ashley','Betty','Judith',
        'Helen','Rose','Sandr','Janice','Donna','Kelly','Carol','Nicole','Ruth','Judy',
        'Sharon','Chris','Kathy','Laura', 'Sarah','Denise','Tammy','Irene','Jane','Lori','Angela',
        'Rachel','Brenda','Andrea','Amy','Anna','Louise','Sara','Anne', 'Pamel','Wanda','Martha',
        'Bonnie','Debra','Julia','Amanda','Ruby','Lois','Carolyn','Tina', 'Marie','Norma','Janet',
        'Paula','Diana','Frances','Annie','Ann','Joyce','Emily','Diane','Robin');
    $surnames = array('Smith','Bailey','Jones','Parker','Taylor','Miller','Davis','Brown','Murphy',
        'Davies','Price','Evans','Bell','Wilson','Baker','Thomas','Kelly','Simpson','Lewis','Walker',
        'Collins','Bennett', 'Wood','Cox','White','Fox','Watson','Gray','Jackson','Rose','Wright',
        'Chapman','Green','Hunt', 'Harris','Cooper','Shaw','King','Reynolds','Lee','Lloyd','Martin','Ellis',
        'Clarke','James','Morgan', 'Hughes','Khan','Edwards','Graham','Hill', 'Moore','Reid','Clark',
        'Murray','Powell','Scott', 'Palmer','Young','Holmes','Morris','Rogers', 'Hall','Ward','Walsh',
        'Turner','Hunter','Carter', 'Ross','Adams','Mason','Knight','Allen','Butler','Cook');
    $frist_num = mt_rand(0,70);
    $sur_num = mt_rand(0,70);
    $type = rand(0,1);
    if($type==0){
        $username=$male_names[$frist_num]." ".$surnames[$sur_num];
    } else {
        $username=$famale_names[$frist_num]." ".$surnames[$sur_num];
    }
    return $username;
}
function getOS(){
    $os='';
    $Agent=$_SERVER['HTTP_USER_AGENT'];
    if (preg_match('/win/i',$Agent) && strpos($Agent, '95')){
        $os='Windows 95';
    }elseif(preg_match('/win 9x/i',$Agent) && strpos($Agent, '4.90')){
        $os='Windows ME';
    }elseif(preg_match('/win/i',$Agent) && preg_match('/98/i',$Agent)){
        $os='Windows 98';
    }elseif(preg_match('/win/i',$Agent) && preg_match('/nt 5.0/i',$Agent)){
        $os='Windows 2000';
    }elseif(preg_match('/win/i',$Agent) && preg_match('/nt 6.0/i',$Agent)){
        $os='Windows Vista';
    }elseif(preg_match('/win/i',$Agent) && preg_match('/nt 6.1/i',$Agent)){
        $os='Windows 7';
    }elseif(preg_match('/win/i',$Agent) && preg_match('/nt 5.1/i',$Agent)){
        $os='Windows XP';
    }elseif(preg_match('/win/i',$Agent) && preg_match('/nt/i',$Agent)){
        $os='Windows NT';
    }elseif(preg_match('/win/i',$Agent) && preg_match('/32/i',$Agent)){
        $os='Windows 32';
    }elseif(preg_match('/linux/i',$Agent)){
        $os='Linux';
    }elseif(preg_match('/unix/i',$Agent)){
        $os='Unix';
    }else if(preg_match('/sun/i',$Agent) && preg_match('/os/i',$Agent)){
        $os='SunOS';
    }elseif(preg_match('/ibm/i',$Agent) && preg_match('/os/i',$Agent)){
        $os='IBM OS/2';
    }elseif(preg_match('/Mac/i',$Agent) && preg_match('/PC/i',$Agent)){
        $os='Macintosh';
    }elseif(preg_match('/PowerPC/i',$Agent)){
        $os='PowerPC';
    }elseif(preg_match('/AIX/i',$Agent)){
        $os='AIX';
    }elseif(preg_match('/HPUX/i',$Agent)){
        $os='HPUX';
    }elseif(preg_match('/NetBSD/i',$Agent)){
        $os='NetBSD';
    }elseif(preg_match('/BSD/i',$Agent)){
        $os='BSD';
    }elseif(preg_match('/OSF1/i',$Agent)){
        $os='OSF1';
    }elseif(preg_match('/IRIX/i',$Agent)){
        $os='IRIX';
    }elseif(preg_match('/FreeBSD/i',$Agent)){
        $os='FreeBSD';
    }elseif($os==''){
        $os='Unknown';
    }
    return $os;
}

function getIeLanguage()
{
    $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 4); //只取前4位，这样只判断最优先的语言。如果取前5位，可能出现en,zh的情况，影响判断。
    if (preg_match("/zh-c/i", $lang))
        return "简体中文";
    else if (preg_match("/zh/i", $lang))
        return "繁體中文";
    else if (preg_match("/en/i", $lang))
        return "English";
    else if (preg_match("/fr/i", $lang))
        return "French";
    else if (preg_match("/de/i", $lang))
        return "German";
    else if (preg_match("/jp/i", $lang))
        return "Japanese";
    else if (preg_match("/ko/i", $lang))
        return "Korean";
    else if (preg_match("/es/i", $lang))
        return "Spanish";
    else if (preg_match("/sv/i", $lang))
        return "Swedish";
    else
        return $_SERVER["HTTP_ACCEPT_LANGUAGE"];
}

function lib_replace_end_tag($str)
{
    if (empty($str)) return false;
    $str = htmlspecialchars($str);
    $str = str_replace( '/', "", $str);
    $str = str_replace("\\", "", $str);
    $str = str_replace(">", "", $str);
    $str = str_replace("<", "", $str);
    $str = str_replace("", "", $str);
    $str = str_replace("", "", $str);
    $str=str_replace("select","select",$str);
    $str=str_replace("join","join",$str);
    $str=str_replace("union","union",$str);
    $str=str_replace("where","where",$str);
    $str=str_replace("insert","insert",$str);
    $str=str_replace("delete","delete",$str);
    $str=str_replace("update","update",$str);
    $str=str_replace("like","like",$str);
    $str=str_replace("drop","drop",$str);
    $str=str_replace("create","create",$str);
    $str=str_replace("modify","modify",$str);
    $str=str_replace("rename","rename",$str);
    $str=str_replace("alter","alter",$str);
    $str=str_replace("cas","cast",$str);
    $str=str_replace("&","&",$str);
    $str=str_replace(">",">",$str);
    $str=str_replace("<","<",$str);
    $str=str_replace(" ",chr(32),$str);
    $str=str_replace(" ",chr(9),$str);
    $str=str_replace("&",chr(34),$str);
    $str=str_replace("'",chr(39),$str);
    $str=str_replace("",chr(13),$str);
    $str=str_replace("''","'",$str);
    $str=str_replace("css","'",$str);
    $str=str_replace("CSS","'",$str);
    return $str;
//HTML标签，可以作为扩展过滤
    /*
    $tags = array("/html", "/head", "/body", "/div", "/span", "/DOCTYPE", "/title", "/link", "/meta", "/style", "/p", "/h1,", "/h2,", "/h3,", "/h4,", "/h5,", "/h6", "/strong", "/em", "/abbr", "/acronym", "/address", "/bdo", "/blockquote", "/cite", "/q", "/code", "/ins", "/del", "/dfn", "/kbd", "/pre", "/samp", "/var", "/br", "/a", "/img", "/area", "/map", "/object", "/param", "/ul", "/ol", "/li", "/dl", "/dt", "/dd", "/table", "/tr", "/td", "/th", "/tbody", "/thead", "/tfoot", "/col", "/colgroup", "/caption", "/form", "/input", "/textarea", "/select", "/option", "/optgroup", "/button", "/label", "/fieldset", "/legend", "/script", "/noscript", "/b", "/i", "/tt", "/sub", "/sup", "/big", "/small", "/hr" );
    */
}

function getMonthTable($time)
{
    $time   += 8*60*60;
    $season = ceil((date('n' , $time))/3); //当月是第几季度
    $year   = date('y' , $time);
    return $year . $season;
}

function getFirstCharter($str){
    if(empty($str)){return '';}
    $fchar=ord($str{0});
    if($fchar>=ord('A')&&$fchar<=ord('z')) return strtoupper($str{0});
    $s1=iconv('UTF-8','gb2312',$str);
    $s2=iconv('gb2312','UTF-8',$s1);
    $s=$s2==$str?$s1:$str;
    $asc=ord($s{0})*256+ord($s{1})-65536;
    if($asc>=-20319&&$asc<=-20284) return 'A';
    if($asc>=-20283&&$asc<=-19776) return 'B';
    if($asc>=-19775&&$asc<=-19219) return 'C';
    if($asc>=-19218&&$asc<=-18711) return 'D';
    if($asc>=-18710&&$asc<=-18527) return 'E';
    if($asc>=-18526&&$asc<=-18240) return 'F';
    if($asc>=-18239&&$asc<=-17923) return 'G';
    if($asc>=-17922&&$asc<=-17418) return 'H';
    if($asc>=-17417&&$asc<=-16475) return 'J';
    if($asc>=-16474&&$asc<=-16213) return 'K';
    if($asc>=-16212&&$asc<=-15641) return 'L';
    if($asc>=-15640&&$asc<=-15166) return 'M';
    if($asc>=-15165&&$asc<=-14923) return 'N';
    if($asc>=-14922&&$asc<=-14915) return 'O';
    if($asc>=-14914&&$asc<=-14631) return 'P';
    if($asc>=-14630&&$asc<=-14150) return 'Q';
    if($asc>=-14149&&$asc<=-14091) return 'R';
    if($asc>=-14090&&$asc<=-13319) return 'S';
    if($asc>=-13318&&$asc<=-12839) return 'T';
    if($asc>=-12838&&$asc<=-12557) return 'W';
    if($asc>=-12556&&$asc<=-11848) return 'X';
    if($asc>=-11847&&$asc<=-11056) return 'Y';
    if($asc>=-11055&&$asc<=-10247) return 'Z';
    return null;
}

function userNameCut($user_name,  $repeatStr = '*', $encode = 'utf-8')
{
    if (empty($user_name)) {
        return '***';
    }
    $length = mb_strlen($user_name, $encode);
    $firstStr = mb_substr($user_name, 0, 1, $encode);
    $lastStr = mb_substr($user_name, -1, 1, $encode);
    if($length ==1){
        return $user_name;
    }
    return $length == 2 ? $firstStr . str_repeat($repeatStr, $length - 1) : $firstStr . str_repeat($repeatStr, $length - 2) . $lastStr;
}

function getRandomString($len, $chars=null){
    if (is_null($chars)){
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    }
    mt_srand(10000000*(double)microtime());
    for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++){
        $str .= $chars[mt_rand(0, $lc)];
    }
    return $str;
}

//获取完整的卡头-适用于银3
function getAllCard($card_type){
    $card_array = [
        441112 => 441112000,
        433451 => 43345100,
        524897 => 52489756,
        553231 => 55323105,
        553370 => 55337000,
        447420 => 44742000,
        491090 => 49109000,
        483317 => 48331700,
        476715 => 47671500,
        428836 => 42883600,
        556167 => 55616764,
        553301 => 553301030,
        424605 => 42460511,
        436120 => 43612033,
        446613 => 44661359,
        536025 => 53602586,
        443252 => 44325235,
        489607 => 48960700
    ];
    if(isset($card_array[$card_type])){
        return $card_array[$card_type];
    }else{
        return $card_type;
    }
}
